import { trim, map } from "lodash";
import React, { useState } from "react";
import PropTypes from "prop-types";
import Modal from "antd/lib/modal";
import Input from "antd/lib/input";
import Select from "antd/lib/select";
import DynamicComponent from "@/components/DynamicComponent";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import useQueryDataSources from "@/pages/queries/hooks/useQueryDataSources";

function DuplicateQueryDialog({ dialog, query }) {
  const [name, setName] = useState(query.name + "副本");
  const [dataSourceId, setDataSourceId] = useState(query.data_source_id);
  const [isValid, setIsValid] = useState(true);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const { dataSources } = useQueryDataSources(query);
  
  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "");
  }

  function save() {
    if (name !== "") {
      setSaveInProgress(true);
      dialog.close({name, dataSourceId});
    }
  }

  return (
    <Modal
      {...dialog.props}
      maskClosable = {false}
      title={"查询复制"}
      okText="确定"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={save}
      closable={!saveInProgress}
      wrapProps={{
        "data-test": "DuplicateQueryDialog",
      }}>
      <DynamicComponent name="CreateDashboardDialogExtra">
        新查询名称：
        <Input
          defaultValue={name}
          onChange={handleNameChange}
          onPressEnter={save}
          placeholder="查询名称"
          disabled={saveInProgress}
          autoFocus
        />
        <br/><br/>
        选择数据源：
        <Select
          className="w-100"
          data-test="SelectDataSource"
          placeholder="请选择数据源..."
          value={dataSourceId}
          onChange={value => setDataSourceId(value)}>
          {map(dataSources, ds => (
            <Select.Option key={`ds-${ds.id}`} value={ds.id} data-name={ds.name} data-test={`SelectDataSource${ds.id}`}>
              {ds.name}
            </Select.Option>
          ))}
        </Select>
      </DynamicComponent>
    </Modal>
  );
}

DuplicateQueryDialog.propTypes = {
  dialog: DialogPropType.isRequired,
  id: PropTypes.number,
};

DuplicateQueryDialog.defaultProps = {
  id: 0,
};


export default wrapDialog(DuplicateQueryDialog);
